package br.com.post.persistence;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.post.model.Text;

public class TextDao {
	private static TextDao instance;
	/**
	 * Persiste texto no banco
	 * @param text
	 */
	public void createText(Text text) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.save(text);
		tx.commit();
		session.close();
	}
	
	/**
	 * Atualiza o texto no banco
	 * @param text
	 */
	public void updateText(Text text) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.merge(text);
		tx.commit();
		session.close();
	}
	
	/**
	 * Seleciona um texto no banco de acordo com o id(long)
	 * @param text_id
	 * @return text
	 */
	public Text selectText(long text_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Text text = (Text)session.get(Text.class,text_id);
		tx.commit();
		session.close();
		return text;
	}
	
	/**
	 * Deleta o texto de acordo com o id, primeiro faz um select
	 * para o hibernate entender, depois remove o texto selecionado
	 * @param text_id
	 */
	public void deleteText(long text_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Text text = selectText(text_id);
		session.delete(text);
		tx.commit();
		session.close();
	}

	public static TextDao getInstance() {
		if(instance == null)
			instance = new TextDao();
		return instance;
	}

	public static void setInstance(TextDao instance) {
		TextDao.instance = instance;
	}
	
	@SuppressWarnings("unchecked")
	public List<Text> getList(){
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		List<Text> textos  = session.createQuery("from Text t order by t.text_title").list();
		tx.commit();
		session.close();
		return textos;
	}
	
	@SuppressWarnings("unchecked")
	public List<Text> listByTopic(int topic_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		List<Text> listText = session.createQuery("FROM Text t where t.text_topic_id="+topic_id).list();
		tx.commit();
		session.close();
		return listText;
	}
	
	
	
}

